$(function () {
    var l = abp.localization.getResource("FreeCare");
	
	var medicationService = window.sanJ.freeCare.medications.medications;
	
	
    var createModal = new abp.ModalManager({
        viewUrl: abp.appPath + "Medications/CreateModal",
        scriptUrl: abp.appPath + "Pages/Medications/createModal.js",
        modalClass: "medicationCreate"
    });

	var editModal = new abp.ModalManager({
        viewUrl: abp.appPath + "Medications/EditModal",
        scriptUrl: abp.appPath + "Pages/Medications/editModal.js",
        modalClass: "medicationEdit"
    });

	var getFilter = function() {
        return {
            filterText: $("#FilterText").val(),
            code: $("#CodeFilter").val(),
			statusCode: $("#StatusCodeFilter").val(),
			keyWord: $("#KeyWordFilter").val(),
			productName: $("#ProductNameFilter").val(),
			productNamePY: $("#ProductNamePYFilter").val(),
			productNameWB: $("#ProductNameWBFilter").val(),
			productNameEN: $("#ProductNameENFilter").val(),
			alias: $("#AliasFilter").val(),
			aliasPY: $("#AliasPYFilter").val(),
			aliasWB: $("#AliasWBFilter").val(),
			aliasEN: $("#AliasENFilter").val(),
			scientificName: $("#ScientificNameFilter").val(),
			scientificNamePY: $("#ScientificNamePYFilter").val(),
			scientificNameWB: $("#ScientificNameWBFilter").val(),
			scientificNameEN: $("#ScientificNameENFilter").val(),
			antiLevelCode: $("#AntiLevelCodeFilter").val(),
			antiClassCode1: $("#AntiClassCode1Filter").val(),
			antiClassCode2: $("#AntiClassCode2Filter").val(),
			anitDDDUnitCode: $("#AnitDDDUnitCodeFilter").val(),
			anitDDDValueMin: $("#AnitDDDValueFilterMin").val(),
			anitDDDValueMax: $("#AnitDDDValueFilterMax").val(),
			antiOnceMinValueMin: $("#AntiOnceMinValueFilterMin").val(),
			antiOnceMinValueMax: $("#AntiOnceMinValueFilterMax").val(),
			antiOnceMaxValueMin: $("#AntiOnceMaxValueFilterMin").val(),
			antiOnceMaxValueMax: $("#AntiOnceMaxValueFilterMax").val(),
			antiOnceUnitCode: $("#AntiOnceUnitCodeFilter").val(),
			antiFrequencyMinMin: $("#AntiFrequencyMinFilterMin").val(),
			antiFrequencyMinMax: $("#AntiFrequencyMinFilterMax").val(),
			antiFrequencyMaxMin: $("#AntiFrequencyMaxFilterMin").val(),
			antiFrequencyMaxMax: $("#AntiFrequencyMaxFilterMax").val(),
			gBCode: $("#GBCodeFilter").val(),
			typeCode: $("#TypeCodeFilter").val(),
			classCode: $("#ClassCodeFilter").val(),
			feeTypeCode: $("#FeeTypeCodeFilter").val(),
			specialTypeCode: $("#SpecialTypeCodeFilter").val(),
			levelCode: $("#LevelCodeFilter").val(),
			doseFormCode: $("#DoseFormCodeFilter").val(),
			specification: $("#SpecificationFilter").val(),
			baseUnitCode: $("#BaseUnitCodeFilter").val(),
			clinicSaleUnitCode: $("#ClinicSaleUnitCodeFilter").val(),
			clinicSaleVolumeMin: $("#ClinicSaleVolumeFilterMin").val(),
			clinicSaleVolumeMax: $("#ClinicSaleVolumeFilterMax").val(),
			inpatientSaleUnitCode: $("#InpatientSaleUnitCodeFilter").val(),
			inpatientSaleVolume: $("#InpatientSaleVolumeFilter").val(),
			transportUnitCode: $("#TransportUnitCodeFilter").val(),
			transportVolume: $("#TransportVolumeFilter").val(),
			defaultDoseUnitCode: $("#DefaultDoseUnitCodeFilter").val(),
			defultDoseVolumeMin: $("#DefultDoseVolumeFilterMin").val(),
			defultDoseVolumeMax: $("#DefultDoseVolumeFilterMax").val(),
			secondDoseUnitCode: $("#SecondDoseUnitCodeFilter").val(),
			secondDoseVolumeMin: $("#SecondDoseVolumeFilterMin").val(),
			secondDoseVolumeMax: $("#SecondDoseVolumeFilterMax").val(),
			retailPriceMin: $("#RetailPriceFilterMin").val(),
			retailPriceMax: $("#RetailPriceFilterMax").val(),
			defaultUsageCode: $("#DefaultUsageCodeFilter").val(),
			defaultFrequencyCode: $("#DefaultFrequencyCodeFilter").val(),
			defaultDoseVolumeMin: $("#DefaultDoseVolumeFilterMin").val(),
			defaultDoseVolumeMax: $("#DefaultDoseVolumeFilterMax").val(),
			skinTestFlag: $("#SkinTestFlagFilter").val(),
			skinTestNeedFlag: $("#SkinTestNeedFlagFilter").val(),
			skinTestTypeFlag: $("#SkinTestTypeFlagFilter").val(),
			skinTestCode: $("#SkinTestCodeFilter").val()
        };
    };
    
    //<suite-custom-code-block-1>
    //</suite-custom-code-block-1>
    
    var dataTableColumns = [
            {
                rowAction: {
                    items:
                        [
                            {
                                text: l("Edit"),
                                visible: abp.auth.isGranted('FreeCare.Medications.Edit'),
                                action: function (data) {
                                    editModal.open({
                                     id: data.record.id
                                     });
                                }
                            },
                            {
                                text: l("Delete"),
                                visible: abp.auth.isGranted('FreeCare.Medications.Delete'),
                                confirmMessage: function () {
                                    return l("DeleteConfirmationMessage");
                                },
                                action: function (data) {
                                    medicationService.delete(data.record.id)
                                        .then(function () {
                                            abp.notify.info(l("SuccessfullyDeleted"));
                                            dataTable.ajax.reloadEx();;
                                        });
                                }
                            }
                        ]
                },
                width: "1rem"
            },
			{ data: "code" },
			{ data: "statusCode" },
			{ data: "keyWord" },
			{ data: "productName" },
			{ data: "productNamePY" },
			{ data: "productNameWB" },
			{ data: "productNameEN" },
			{ data: "alias" },
			{ data: "aliasPY" },
			{ data: "aliasWB" },
			{ data: "aliasEN" },
			{ data: "scientificName" },
			{ data: "scientificNamePY" },
			{ data: "scientificNameWB" },
			{ data: "scientificNameEN" },
			{ data: "antiLevelCode" },
			{ data: "antiClassCode1" },
			{ data: "antiClassCode2" },
			{ data: "anitDDDUnitCode" },
			{ data: "anitDDDValue" },
			{ data: "antiOnceMinValue" },
			{ data: "antiOnceMaxValue" },
			{ data: "antiOnceUnitCode" },
			{ data: "antiFrequencyMin" },
			{ data: "antiFrequencyMax" },
			{ data: "gBCode" },
			{ data: "typeCode" },
			{ data: "classCode" },
			{ data: "feeTypeCode" },
			{ data: "specialTypeCode" },
			{ data: "levelCode" },
			{ data: "doseFormCode" },
			{ data: "specification" },
			{ data: "baseUnitCode" },
			{ data: "clinicSaleUnitCode" },
			{ data: "clinicSaleVolume" },
			{ data: "inpatientSaleUnitCode" },
			{ data: "inpatientSaleVolume" },
			{ data: "transportUnitCode" },
			{ data: "transportVolume" },
			{ data: "defaultDoseUnitCode" },
			{ data: "defultDoseVolume" },
			{ data: "secondDoseUnitCode" },
			{ data: "secondDoseVolume" },
			{ data: "retailPrice" },
			{ data: "defaultUsageCode" },
			{ data: "defaultFrequencyCode" },
			{ data: "defaultDoseVolume" },
			{ data: "skinTestFlag" },
			{ data: "skinTestNeedFlag" },
			{ data: "skinTestTypeFlag" },
			{ data: "skinTestCode" }        
    ];
    
    
    
    if(abp.auth.isGranted('FreeCare.Medications.Delete')) {
        dataTableColumns.unshift({
                targets: 0,
                data: null,
                orderable: false,
                className: 'select-checkbox',
                width: "0.5rem",
                render: function (data) {
                    return '<input type="checkbox" class="form-check-input select-row-checkbox" data-id="' + data.id + '"/>'
            }
        });
    }
    else {
        $("#BulkDeleteCheckboxTheader").remove();
    }

    var dataTable = $("#MedicationsTable").DataTable(abp.libs.datatables.normalizeConfiguration({
        processing: true,
        serverSide: true,
        paging: true,
        searching: false,
        scrollX: true,
        autoWidth: true,
        scrollCollapse: true,
        order: [[2, "asc"]],
        ajax: abp.libs.datatables.createAjax(medicationService.getList, getFilter),
        columnDefs: dataTableColumns
    }));
    
    
    dataTable.on("xhr", function () {
       selectOrUnselectAllCheckboxes(false);
       showOrHideContextMenu();
        $("#select_all").prop("indeterminate", false);
        $("#select_all").prop("checked", false);
    });    
    
    function selectOrUnselectAllCheckboxes(selectAll) {
        $(".select-row-checkbox").each(function () {
            $(this).prop("checked", selectAll);
        });
    }


    $("#select_all").click(function () {
        if($(this).is(":checked")) {
            selectOrUnselectAllCheckboxes(true);
        }
        else {
            $(".select-row-checkbox").each(function () {
                selectOrUnselectAllCheckboxes(false);
            });
        }

        showOrHideContextMenu();
    });
    
    dataTable.on("change", "input[type='checkbox'].select-row-checkbox", function () {
       var unSelectedCheckboxes = $("input[type='checkbox'].select-row-checkbox:not(:checked)");
       
       if(unSelectedCheckboxes.length >= 1) {
           var dataRecordTotal = dataTable.context[0].json.data.length;
           if(unSelectedCheckboxes.length === dataRecordTotal) {
               $("#select_all").prop("indeterminate", false);
               $("#select_all").prop("checked", false);
           }
           else {
               $("#select_all").prop("indeterminate", true);
           }   
       }
       else {
           $("#select_all").prop("indeterminate", false);
           $("#select_all").prop("checked", true);
       }

        showOrHideContextMenu();
    });
    
    var showOrHideContextMenu = function () {
        var selectedCheckboxes = $("input[type='checkbox'].select-row-checkbox:is(:checked)");
        var selectedCheckboxCount = selectedCheckboxes.length;
        var dataRecordTotal = dataTable.context[0].json.data.length;
        var recordsTotal = dataTable.context[0].json.recordsTotal;
        
        if(selectedCheckboxCount >= 1) {
            $("#bulk-delete-context-menu").removeClass("d-none");
            
            $("#items-selected-info-message").html(
                selectedCheckboxCount === 1
                ? l("OneItemOnThisPageIsSelected")
                : l("NumberOfItemsOnThisPageAreSelected", selectedCheckboxCount));
            
            $("#items-selected-info-message").removeClass("d-none");
            
            if(selectedCheckboxCount === dataRecordTotal && recordsTotal > dataRecordTotal) {
                $("#select-all-items-btn").html(l("SelectAllItems", recordsTotal));
                $("#select-all-items-btn").removeClass("d-none");

                $("#select-all-items-btn").off("click");
                $("#select-all-items-btn").click(function () {
                    $(this).data("selected", true);
                    $(this).addClass("d-none");
                    $("#items-selected-info-message").html(l("AllItemsAreSelected", recordsTotal));
                    $("#clear-selection-btn").removeClass("d-none");
                });
                
                $("#clear-selection-btn").off("click");
                $("#clear-selection-btn").click(function () {
                    $("#select-all-items-btn").data("selected", false);
                    $("#select_all").prop("checked", false);
                    selectOrUnselectAllCheckboxes(false);
                    showOrHideContextMenu();
                });
                
            }
            else {
                $("#select-all-items-btn").addClass("d-none");
                $("#select-all-items-btn").data("selected", false);
                $("#clear-selection-btn").addClass("d-none");
            }
            
            $("#delete-selected-items").off("click");
            $("#delete-selected-items").click(function () {
                if($("#select-all-items-btn").data("selected") === true) {
                    abp.message.confirm(l("DeleteAllRecords"), function (confirmed) {
                       if(!confirmed) {
                           return;
                       } 
                       
                       medicationService.deleteAll(getFilter())
                           .then(function () {
                               dataTable.ajax.reloadEx();
                               selectOrUnselectAllCheckboxes(false);
                               showOrHideContextMenu();
                           });
                    });
                }
                else {
                    var selectedCheckboxes = $("input[type='checkbox'].select-row-checkbox:is(:checked)");
                    var selectedRecordsIds = [];

                    for(var i = 0; i < selectedCheckboxes.length; i++)
                    {
                        selectedRecordsIds.push($(selectedCheckboxes[i]).data("id"));
                    }

                    abp.message.confirm(l("DeleteSelectedRecords", selectedCheckboxes.length), function (confirmed) {
                        if(!confirmed) {
                            return;
                        }

                        medicationService.deleteByIds(selectedRecordsIds)
                            .then(function () {
                                dataTable.ajax.reloadEx();
                                selectOrUnselectAllCheckboxes(false);
                                showOrHideContextMenu();
                            });
                    });
                }
            });
        }
        else {
            $("#bulk-delete-context-menu").addClass("d-none");
            $("#select-all-items-btn").addClass("d-none");
            $("#items-selected-info-message").addClass("d-none");
            $("#clear-selection-btn").addClass("d-none");
        }
    };

    
    //<suite-custom-code-block-2>
    //</suite-custom-code-block-2>

    createModal.onResult(function () {
        dataTable.ajax.reloadEx();;
        selectOrUnselectAllCheckboxes(false);
        showOrHideContextMenu();
    });

    editModal.onResult(function () {
        dataTable.ajax.reloadEx();;
        selectOrUnselectAllCheckboxes(false);
        showOrHideContextMenu();        
    });

    $("#NewMedicationButton").click(function (e) {
        e.preventDefault();
        createModal.open();
    });

	$("#SearchForm").submit(function (e) {
        e.preventDefault();
        dataTable.ajax.reloadEx();;
        selectOrUnselectAllCheckboxes(false);
        showOrHideContextMenu();
    });

    $("#ExportToExcelButton").click(function (e) {
        e.preventDefault();

        medicationService.getDownloadToken().then(
            function(result){
                    var input = getFilter();
                    var url =  abp.appPath + 'api/app/medications/as-excel-file' + 
                        abp.utils.buildQueryString([
                            { name: 'downloadToken', value: result.token },
                            { name: 'filterText', value: input.filterText }, 
                            { name: 'code', value: input.code }, 
                            { name: 'statusCode', value: input.statusCode }, 
                            { name: 'keyWord', value: input.keyWord }, 
                            { name: 'productName', value: input.productName }, 
                            { name: 'productNamePY', value: input.productNamePY }, 
                            { name: 'productNameWB', value: input.productNameWB }, 
                            { name: 'productNameEN', value: input.productNameEN }, 
                            { name: 'alias', value: input.alias }, 
                            { name: 'aliasPY', value: input.aliasPY }, 
                            { name: 'aliasWB', value: input.aliasWB }, 
                            { name: 'aliasEN', value: input.aliasEN }, 
                            { name: 'scientificName', value: input.scientificName }, 
                            { name: 'scientificNamePY', value: input.scientificNamePY }, 
                            { name: 'scientificNameWB', value: input.scientificNameWB }, 
                            { name: 'scientificNameEN', value: input.scientificNameEN }, 
                            { name: 'antiLevelCode', value: input.antiLevelCode }, 
                            { name: 'antiClassCode1', value: input.antiClassCode1 }, 
                            { name: 'antiClassCode2', value: input.antiClassCode2 }, 
                            { name: 'anitDDDUnitCode', value: input.anitDDDUnitCode },
                            { name: 'anitDDDValueMin', value: input.anitDDDValueMin },
                            { name: 'anitDDDValueMax', value: input.anitDDDValueMax },
                            { name: 'antiOnceMinValueMin', value: input.antiOnceMinValueMin },
                            { name: 'antiOnceMinValueMax', value: input.antiOnceMinValueMax },
                            { name: 'antiOnceMaxValueMin', value: input.antiOnceMaxValueMin },
                            { name: 'antiOnceMaxValueMax', value: input.antiOnceMaxValueMax }, 
                            { name: 'antiOnceUnitCode', value: input.antiOnceUnitCode },
                            { name: 'antiFrequencyMinMin', value: input.antiFrequencyMinMin },
                            { name: 'antiFrequencyMinMax', value: input.antiFrequencyMinMax },
                            { name: 'antiFrequencyMaxMin', value: input.antiFrequencyMaxMin },
                            { name: 'antiFrequencyMaxMax', value: input.antiFrequencyMaxMax }, 
                            { name: 'gBCode', value: input.gBCode }, 
                            { name: 'typeCode', value: input.typeCode }, 
                            { name: 'classCode', value: input.classCode }, 
                            { name: 'feeTypeCode', value: input.feeTypeCode }, 
                            { name: 'specialTypeCode', value: input.specialTypeCode }, 
                            { name: 'levelCode', value: input.levelCode }, 
                            { name: 'doseFormCode', value: input.doseFormCode }, 
                            { name: 'specification', value: input.specification }, 
                            { name: 'baseUnitCode', value: input.baseUnitCode }, 
                            { name: 'clinicSaleUnitCode', value: input.clinicSaleUnitCode },
                            { name: 'clinicSaleVolumeMin', value: input.clinicSaleVolumeMin },
                            { name: 'clinicSaleVolumeMax', value: input.clinicSaleVolumeMax }, 
                            { name: 'inpatientSaleUnitCode', value: input.inpatientSaleUnitCode }, 
                            { name: 'inpatientSaleVolume', value: input.inpatientSaleVolume }, 
                            { name: 'transportUnitCode', value: input.transportUnitCode }, 
                            { name: 'transportVolume', value: input.transportVolume }, 
                            { name: 'defaultDoseUnitCode', value: input.defaultDoseUnitCode },
                            { name: 'defultDoseVolumeMin', value: input.defultDoseVolumeMin },
                            { name: 'defultDoseVolumeMax', value: input.defultDoseVolumeMax }, 
                            { name: 'secondDoseUnitCode', value: input.secondDoseUnitCode },
                            { name: 'secondDoseVolumeMin', value: input.secondDoseVolumeMin },
                            { name: 'secondDoseVolumeMax', value: input.secondDoseVolumeMax },
                            { name: 'retailPriceMin', value: input.retailPriceMin },
                            { name: 'retailPriceMax', value: input.retailPriceMax }, 
                            { name: 'defaultUsageCode', value: input.defaultUsageCode }, 
                            { name: 'defaultFrequencyCode', value: input.defaultFrequencyCode },
                            { name: 'defaultDoseVolumeMin', value: input.defaultDoseVolumeMin },
                            { name: 'defaultDoseVolumeMax', value: input.defaultDoseVolumeMax }, 
                            { name: 'skinTestFlag', value: input.skinTestFlag }, 
                            { name: 'skinTestNeedFlag', value: input.skinTestNeedFlag }, 
                            { name: 'skinTestTypeFlag', value: input.skinTestTypeFlag }, 
                            { name: 'skinTestCode', value: input.skinTestCode }
                            ]);
                            
                    var downloadWindow = window.open(url, '_blank');
                    downloadWindow.focus();
            }
        )
    });

    $('#AdvancedFilterSectionToggler').on('click', function (e) {
        $('#AdvancedFilterSection').toggle();
    });

    $('#AdvancedFilterSection').on('keypress', function (e) {
        if (e.which === 13) {
            dataTable.ajax.reloadEx();
            selectOrUnselectAllCheckboxes(false);
            showOrHideContextMenu();
        }
    });

    $('#AdvancedFilterSection select').change(function() {
        dataTable.ajax.reloadEx();
        selectOrUnselectAllCheckboxes(false);
        showOrHideContextMenu();
    });
    
    //<suite-custom-code-block-3>
    //</suite-custom-code-block-3>
    
    
    
    
    
    
});
